namespace Billing2
{
    using AjaxControlToolkit;
    using ICSharpCode.SharpZipLib.Zip;
    using Billing2.Controls;
    using System;
    using System.Data;
    using System.IO;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.Security.Application;
    using MyLib;

    public class DownloadBillReport : Page
    {
        protected Button BtnDownload;
        protected ConfirmButtonExtender BtnDownload_ConfirmButtonExtender;
        protected Button BtnRetrieve;
        protected DropDownList ddlBillCust;
        protected DropDownList ddlBillPeriod;
        protected DropDownList ddlCostCentre;
        protected DropDownList ddlOrganization;
        protected DropDownList ddlSite;
        protected CheckBox cbIncludeOldVersion;
        private DataTable dt;
        protected GridView gvwReports;
        protected Label lblAvailable;
        protected Label lblBillCust;
        protected Label lblCC;
        protected Label lblOrg;
        protected Label lblSite;
        protected ucHighlight ucHighlight1;
        protected ucPageTitle ucPageTitle1;
        protected UpdatePanel updatePanel1;
        protected UpdatePanel updatePanel2;
        protected UpdatePanel updatePanel7;
        protected UpdateProgress updateprogress1;
        protected HiddenField xReportID;

        private void BindBillPeriod()
        {
            ClsBillPeriod cls1 = new ClsBillPeriod();
            if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
            {
                this.ddlBillPeriod.DataSource = cls1.SelectReleasedPeriodByBillingRecipientEmail(LoginUser.UserID, LoginUser.Email);
            }
            else
            {
                this.ddlBillPeriod.DataSource = cls1.SelectReleasedPeriodBySiteID(LoginUser.SiteID);
            }
            this.ddlBillPeriod.DataTextField = "ServiceMonth";
            this.ddlBillPeriod.DataValueField = "ID";
            this.ddlBillPeriod.DataBind();
            DataTable dtCurrentPeriod = cls1.SelectCurrentPreiod();
            if ((dtCurrentPeriod.Rows != null) && (dtCurrentPeriod.Rows.Count > 0))
            {
                this.BillPeriodID = dtCurrentPeriod.Rows[0]["ID"].ToString();
            }
        }

        private void BindDLLBillCustomer()
        {
            DataTable dt1 = new ClsBillCustomer().SelectByBillingRecipientEmail(LoginUser.Email);
            this.ddlBillCust.Items.Clear();
            this.ddlBillCust.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlBillCust.Items.Add(
                    new ListItem(
                        Common.EscapeName(dt1.Rows[i]["CustName1"].ToString()) + " - " + Common.EscapeName(dt1.Rows[i]["BillType"].ToString()),
                        Common.EscapeInteger(dt1.Rows[i]["ID"].ToString())));
            }
        }

        private void BindDLLCostCentre()
        {
            ClsCostCentresInSite cls = new ClsCostCentresInSite();
            if (this.ddlSite.SelectedIndex <= 0)
            {
                cls.SiteID = 0;
            }
            else
            {
                cls.SiteID = Convert.ToInt64(this.ddlSite.SelectedValue);
            }
            DataTable dt1 = cls.SelectBySiteID();
            this.ddlCostCentre.Items.Clear();
            this.ddlCostCentre.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlCostCentre.Items.Add(
                    new ListItem(
                        Common.EscapeCostCenterName(dt1.Rows[i]["CostCentreIDName"].ToString()),
                        Common.EscapeInteger(dt1.Rows[i]["ID"].ToString())));
            }
        }

        private void BindDLLOrganization()
        {
            DataTable dt1 = new ClsOrganization().SelectAll();
            this.ddlOrganization.Items.Clear();
            this.ddlOrganization.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlOrganization.Items.Add(
                    new ListItem(
                        Common.EscapeCostCenterName(dt1.Rows[i]["OrgIDName"].ToString()),
                        Common.EscapeInteger(dt1.Rows[i]["ID"].ToString())));
            }
            this.BindDLLSitesInOrganization();
        }

        private void BindDLLSitesInOrganization()
        {
            ClsSitesInOrganization cls = new ClsSitesInOrganization();
            if (this.ddlOrganization.SelectedIndex <= 0)
            {
                cls.OrgID = 0;
            }
            else
            {
                cls.OrgID = Convert.ToInt64(this.ddlOrganization.SelectedValue);
            }
            DataTable dt1 = cls.SelectByOrgID();
            this.ddlSite.Items.Clear();
            this.ddlSite.Items.Add(new ListItem("ALL", "0"));
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                this.ddlSite.Items.Add(
                    new ListItem(
                        Common.EscapeCostCenterName(dt1.Rows[i]["SiteIDName"].ToString()),
                        Common.EscapeInteger(dt1.Rows[i]["ID"].ToString())));
            }
            this.BindDLLCostCentre();
        }

        private DataTable BindGridViewData()
        {
            ClsBillReportRepository cls1 = new ClsBillReportRepository();
            if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
            {
                this.dt = cls1.SelectAllReleasedWithoutDataByPeriodLoginGroupLoginEmailBillCustomer(Convert.ToInt64(this.BillPeriodID), LoginUser.GroupID, LoginUser.UserID, LoginUser.Email, Convert.ToInt64(this.ddlBillCust.SelectedValue), cbIncludeOldVersion.Checked ? 1 : 0);
            }
            else
            {
                this.dt = cls1.SelectAllReleasedWithoutDataByPeriodLoginGroupLoginSiteOrgSiteCC(Convert.ToInt64(this.BillPeriodID), LoginUser.GroupID, LoginUser.SiteID, Convert.ToInt64(this.ddlOrganization.SelectedValue), Convert.ToInt64(this.ddlSite.SelectedValue), Convert.ToInt64(this.ddlCostCentre.SelectedValue), cbIncludeOldVersion.Checked ? 1 : 0);
            }
            if (this.dt != null)
            {
                this.gvwReports.DataSource = this.dt;
                this.gvwReports.DataBind();
                if (this.dt.Rows.Count == 0)
                {
                    this.lblAvailable.Visible = false;
                    this.BtnDownload.Visible = false;
                    this.ucHighlight1.Message = "No report available for current selection.";
                }
                else
                {
                    this.lblAvailable.Visible = true;
                    this.BtnDownload.Visible = this.Read0;
                }
            }
            return this.dt;
        }

        protected void BtnDownload_Click(object sender, EventArgs e)
        {
            int iCheckCount = 0;
            foreach (GridViewRow row in this.gvwReports.Rows)
            {
                CheckBox chkbox = (CheckBox) row.FindControl("GRChkBox");
                if (chkbox.Checked)
                {
                    iCheckCount++;
                }
            }
            if (iCheckCount == 0)
            {
                this.ucHighlight1.ErrorMessage = "Please select at least one report for processing";
            }
            else
            {
                //string strFile = ClsUtilityHelper.GenerateId();
                string filename = MyLib.Rand.RandomDigitLowercaseUppercase(32);
                if (!Common.ValidFileName(filename))
                {
                    this.ucHighlight1.ErrorMessage = "invalid filename!";
                    return;
                }
                filename = base.Server.MapPath("./") + filename + ".zip";

                ZipOutputStream zipOS;
                try
                {
                    zipOS = new ZipOutputStream(File.Create(filename));
                    zipOS.SetLevel(9);
                    ClsBillReportRepository ClsRepo = new ClsBillReportRepository();
                    foreach (GridViewRow row in this.gvwReports.Rows)
                    {
                        CheckBox chk1 = (CheckBox)row.FindControl("GRChkBox");
                        if (chk1.Checked)
                        {
                            Label lblRepoID = (Label)row.FindControl("lblRepositoryID");
                            ClsRepo.ID = Convert.ToInt64(lblRepoID.Text);
                            DataTable dt1 = ClsRepo.Select();
                            if ((dt1 != null) && (dt1.Rows.Count > 0))
                            {
                                byte[] bytes = (byte[])dt1.Rows[0]["ReportData"];
                                ZipEntry zipEntry = new ZipEntry(dt1.Rows[0]["ReportFileName"].ToString());
                                zipOS.PutNextEntry(zipEntry);
                                zipOS.Write(bytes, 0, bytes.Length);
                            }
                        }
                    }
                    zipOS.Finish();
                    zipOS.Close();
                }
                finally
                {
                    zipOS = null;
                }
                base.Response.ClearContent();
                base.Response.Clear();
                base.Response.ContentType = "application/zip";
                base.Response.AppendHeader("Content-Disposition", "attachment; filename=download.zip;");
                //base.Response.TransmitFile(filename);

                FileStream fs = new FileStream(filename, FileMode.Open);
                byte[] buffer = new byte[(int)fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();
                base.Response.BinaryWrite(buffer);

                //base.Response.Flush();
                //base.Response.Close();
                base.Response.End();
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
            }
        }

        protected void BtnRetrieve_Click(object sender, EventArgs e)
        {
            this.BindGridViewData();
        }

        protected void ddlOrganization_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlOrganization.SelectedIndex != -1)
            {
                this.BindDLLSitesInOrganization();
            }
        }

        protected void ddlSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlSite.SelectedIndex != -1)
            {
                this.BindDLLCostCentre();
            }
        }

        private void GetPermission()
        {
            ClsACLHelper cls = new ClsACLHelper();
            string pageName = this.Page.ToString().Substring(4, this.Page.ToString().Substring(4).Length - 5) + ".aspx";
            cls.SetPermission(LoginUser.TreeMenu, pageName);
            this.Read0 = cls.Read0;
            this.BtnRetrieve.Visible = cls.Read0;
            if (!cls.Read0)
            {
                base.Response.Redirect("logout.aspx", true);
            }
        }

        protected void GRChkALL_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkALL = (CheckBox) this.gvwReports.HeaderRow.FindControl("GRChkALL");
            foreach (GridViewRow row in this.gvwReports.Rows)
            {
                CheckBox chk1 = (CheckBox) row.FindControl("GRChkBox");
                if (chkALL.Checked)
                {
                    chk1.Checked = true;
                }
                else
                {
                    chk1.Checked = false;
                }
            }
        }

        protected void GRChkBox_CheckedChanged(object sender, EventArgs e)
        {
            bool bAllChecked = true;
            CheckBox chk1 = (CheckBox) sender;
            CheckBox chkALL = (CheckBox) this.gvwReports.HeaderRow.FindControl("GRChkALL");
            if (!chk1.Checked)
            {
                chkALL.Checked = false;
            }
            else if (chk1.Checked)
            {
                foreach (GridViewRow row in this.gvwReports.Rows)
                {
                    CheckBox chk2 = (CheckBox) row.FindControl("GRChkBox");
                    if (!chk2.Checked)
                    {
                        bAllChecked = false;
                    }
                }
                if (bAllChecked)
                {
                    chkALL.Checked = true;
                }
            }
        }

        protected void gvwReports_Sorting(object sender, GridViewSortEventArgs e)
        {
            this.dt = new DataView(this.BindGridViewData()) { Sort = e.SortExpression + " " + this.ViewState["SortDirection"].ToString() }.ToTable();
            if (this.ViewState["SortDirection"].ToString() == "ASC")
            {
                this.ViewState["SortDirection"] = "DESC";
            }
            else
            {
                this.ViewState["SortDirection"] = "ASC";
            }
            this.gvwReports.DataSource = this.dt;
            this.gvwReports.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.ucHighlight1.CloseAll();
            if (this.Session["SiteID"] == null)
            {
                base.Response.Redirect("default.aspx", true);
            }
            if (!this.Page.IsPostBack)
            {
                this.ViewState["SortDirection"] = "ASC";
                this.BindBillPeriod();
                this.SetVisibleBillingRecipientRelatedComponent();
                if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
                {
                    this.BindDLLBillCustomer();
                }
                else
                {
                    this.BindDLLOrganization();
                    if (LoginUser.SiteID > 0)
                    {
                        this.ddlOrganization.SelectedValue = Microsoft.Security.Application.Encoder.HtmlEncode(LoginUser.OrganizationID.ToString());
                        this.BindDLLSitesInOrganization();
                        this.ddlSite.SelectedValue = Microsoft.Security.Application.Encoder.HtmlEncode(LoginUser.SiteID.ToString());
                        this.BindDLLCostCentre();
                        this.ddlOrganization.Enabled = false;
                        this.ddlSite.Enabled = false;
                    }
                }
            }
            this.GetPermission();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ViewStateUserKey = Session.SessionID;
        }

        private void SetVisibleBillingRecipientRelatedComponent()
        {
            bool xVisible = false;
            if (LoginUser.GroupName.ToUpper().Equals("BILLING RECIPIENT"))
            {
                xVisible = true;
            }
            else
            {
                xVisible = false;
            }
            this.lblOrg.Visible = !xVisible;
            this.ddlOrganization.Visible = !xVisible;
            this.lblSite.Visible = !xVisible;
            this.ddlSite.Visible = !xVisible;
            this.lblCC.Visible = !xVisible;
            this.ddlCostCentre.Visible = !xVisible;
            this.lblBillCust.Visible = xVisible;
            this.ddlBillCust.Visible = xVisible;
        }

        public string BillPeriodID
        {
            get
            {
                if (this.ddlBillPeriod.SelectedIndex == -1)
                {
                    return "0";
                }
                return this.ddlBillPeriod.SelectedValue;
            }
            set
            {
                this.ddlBillPeriod.SelectedIndex = -1;
                if ((value != "") && (value != "0"))
                {
                    this.ddlBillPeriod.SelectedIndex = this.ddlBillPeriod.Items.IndexOf(this.ddlBillPeriod.Items.FindByValue(value));
                }
            }
        }

        public bool Read0
        {
            get
            {
                return Convert.ToBoolean(this.ViewState["xRead0"]);
            }
            set
            {
                this.ViewState["xRead0"] = value;
            }
        }

        public string ReportID
        {
            get
            {
                return this.xReportID.Value;
            }
        }

        protected void gvwReports_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToString().ToLower() == "editdata")
            {
                this.xReportID.Value = e.CommandArgument.ToString();
            }
        }

        protected void gvwReports_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex > -1)
            {
                long id = Convert.ToInt64(((DataRowView)e.Row.DataItem).Row["BillReportTemplateID"]);
                int version = Convert.ToInt32(((DataRowView)e.Row.DataItem).Row["Version"]);
                
                if (!(id == 1 || id == 9) || version == 1)
                {
                    e.Row.Cells[7].Visible = false;
                    //e.Row.Cells[7].Text = "";
                }
                else
                {
                    e.Row.Cells[7].Visible = true;
                    //e.Row.Cells[7].Text = "View";
                }
            }
        }
    }
}
